package com.goodboys.base.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;


import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
/**
 * Created by CJ on 2018-05-20.
 */
@Component
@Primary
public class RedisClient {

    private Logger logger = LoggerFactory.getLogger(RedisClient.class);

    {
        System.out.println("RedisClient create instance");
    }
    @Autowired
    private JedisPool jedisPool;

    public void set(String key, String value){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.set(key, value);
        } catch(Exception e){
            logger.info("缓存服务器连接失败！");
        }finally {
            //返还到连接池
            jedis.close();
        }
    }

    public void delete(String key){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.del(key);
        } catch(Exception e){
            logger.info("缓存服务器连接失败！");
        }finally {
            //返还到连接池
            jedis.close();
        }
    }


    //设置过期的类型
    public void setExpire(String key, String value, Long expireSecond){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            boolean keyExist = jedis.exists(key);
            // NX是不存在时才set， XX是存在时才set， EX是秒，PX是毫秒
            if (keyExist) {
                jedis.del(key);
            }
            jedis.set(key, value, "NX", "EX", expireSecond);
        } catch(Exception e){
            logger.info("缓存服务器连接失败！");
        }finally {
            //返还到连接池
            jedis.close();
        }
    }

    public boolean isExistKey(String key){
        Jedis jedis = null;
        boolean result = false;
        try {
            jedis = jedisPool.getResource();
            result  =  jedis.exists(key);
        } catch(Exception e){
            logger.info("缓存服务器连接失败！");
        }finally {
            //返还到连接池
            jedis.close();
            return  result;
        }
    }

    public String get(String key){
        String value = "";
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            value = jedis.get(key);
        } catch(Exception e){
            logger.info("缓存服务器连接异常！");
        }finally {
            //返还到连接池
            jedis.close();
        }
        return value;
    }




}
